home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-04 / netprog.zip / NETPROG.TAR / ipc / tim_shmserv.c < prev    next >
C/C++ Source or Header  |  1989-12-17  |  2KB  |  80 lines

  1. #include    <stdio.h>
  2. #include    <sys/types.h>
  3. #include    <sys/ipc.h>
  4. #include    <sys/shm.h>
  5.  
  6. #include    "shm.h"
  7.  
  8. #define    NUMMESG    10000
  9. #define    MESGLEN    2048
  10.  
  11. int    shmid, clisem, servsem;    /* shared memory and semaphore IDs */
  12. Mesg    *mesgptr;        /* ptr to message structure, which is
  13.                    in the shared memory segment */
  14.  
  15. main()
  16. {
  17.     /*
  18.      * Create the shared memory segment, if required,
  19.      * then attach it.
  20.      */
  21.  
  22.     if ( (shmid = shmget(SHMKEY, sizeof(Mesg), 0666 | IPC_CREAT)) < 0)
  23.         err_sys("server: can't get shared memory");
  24.     if ( (mesgptr = (Mesg *) shmat(shmid, (char *) 0, 0)) == (Mesg *) -1)
  25.         err_sys("server: can't attach shared memory");
  26.  
  27.     /*
  28.      * Create two semaphores.  The client semaphore starts out at 1
  29.      * since the client process starts things going.
  30.      */
  31.  
  32.     if ( (clisem = sem_create(SEMKEY1, 1)) < 0)
  33.         err_sys("server: can't create client semaphore");
  34.     if ( (servsem = sem_create(SEMKEY2, 0)) < 0)
  35.         err_sys("server: can't create server semaphore");
  36.  
  37.     server();
  38.  
  39.     /*
  40.      * Detach the shared memory segment and close the semaphores.
  41.      * The client is the last one to use the shared memory, so
  42.      * it'll remove it when it's done.
  43.      */
  44.  
  45.     if (shmdt(mesgptr) < 0)
  46.         err_sys("server: can't detach shared memory");
  47.  
  48.     sem_close(clisem);
  49.     sem_close(servsem);
  50.  
  51.     exit(0);
  52. }
  53.  
  54. server()
  55. {
  56.     int    i;
  57.  
  58.     /*
  59.      * Wait for the client to tell us it's there and ready.
  60.      */
  61.  
  62.     sem_wait(servsem);
  63.     if (mesgptr->mesg_len != MESGLEN)
  64.         err_sys("server: incorrect length");
  65.     if (mesgptr->mesg_type != MESGLEN)
  66.         err_sys("server: incorrect type");
  67.  
  68.     /*
  69.      * Then send messages to the client.
  70.      */
  71.  
  72.     for (i = 0; i < NUMMESG; i++) {
  73.         mesgptr->mesg_len = MESGLEN;
  74.         mesgptr->mesg_type = (i + 1);
  75.  
  76.         sem_signal(clisem);    /* send to client */
  77.         sem_wait(servsem);    /* wait for client to process */
  78.     }
  79. }
  80.